package com.bwie.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.config.MyNacosConfig;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.TUser;
import com.bwie.pojo.UserRole;
import com.bwie.service.TUserService;
import com.bwie.mapper.TUserMapper;
import com.bwie.utils.R;
import com.bwie.vo.LoginVo;
import com.bwie.vo.PageInfoVo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.catalina.User;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author lenovo
 * @description 针对表【t_user】的数据库操作Service实现
 * @createDate 2025-03-21 18:42:38
 */
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements TUserService {

    @Autowired
    private TUserMapper tUserMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MyNacosConfig myNacosConfig;

    @Autowired
    FastFileStorageClient fastFileStorageClient;

    @Autowired
    HttpServletRequest request;

    /**
     * 根据ID查询用户列表
     *
     * @param id
     * @return
     */
    @Override
    public R getUserById(Integer id) {

        TUser tUser = tUserMapper.selectById(id);

        if (tUser == null) {
            return R.ERROR(404, "用户不存在");
        }
        return R.OK(tUser);
    }

    /**
     * 登录
     *
     * @param loginVo
     * @return
     */
    @Override
    public R login(LoginVo loginVo) {

        //判断用户是否存在
        TUser tUser = tUserMapper.selectOne(
                new QueryWrapper<TUser>().lambda().eq(TUser::getUsername, loginVo.getUsername())
        );
        if (tUser == null) {
            return R.ERROR(404, "用户不存在");
        }


        //判断密码是否正确
        if (!tUser.getPassword().equals(loginVo.getPassword())) {
            return R.ERROR(404, "密码错误");
        }

        //生成token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("id", tUser.getId())
                .claim("username", tUser.getUsername())
                .claim("realName", tUser.getRealName())
                .compact();

        //缓存token
        //定义一个key
        String tokenKey = "token-" + tUser.getId();
        redisTemplate.opsForValue().set(tokenKey, token, 120, TimeUnit.MINUTES);

        //返回数据
        tUser.setPassword(null);
        tUser.setToken(token);
        return R.OK(tUser);
    }

    /**
     * 用户条件分页查询
     *
     * @param pageInfoVo
     * @return
     */
    @Override
    public R getUserList(PageInfoVo pageInfoVo) {

        String token = request.getHeader("token");
        if (token == null) {
            return R.ERROR(500, "请先去登录");
        }

        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("id", Integer.class);

        List<UserRole> roleList = tUserMapper.getUserRole(userId);

        //判断当前用户是否为管理员
        Boolean isAdmin = false;
        for (UserRole userRole : roleList) {
            if (userRole.getRoleName().equals("管理员")) {
                isAdmin = true;
                break;
            }
        }

        //定义分页参数
        Page<TUser> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        //获取分页数据
        QueryWrapper<TUser> wrapper = new QueryWrapper<>();

        if (!isAdmin) {
            wrapper.lambda().eq(TUser::getId, userId);
        }

        //添加搜索条件
        if (StringUtils.isNotEmpty(pageInfoVo.getKeyWord())) {

            wrapper.lambda().like(TUser::getUsername, pageInfoVo.getKeyWord())
                    .or().like(TUser::getRealName, pageInfoVo.getKeyWord())
                    .or().like(TUser::getMobile, pageInfoVo.getKeyWord())
                    .or().like(TUser::getEmail, pageInfoVo.getKeyWord());

        }


        wrapper.lambda().orderByDesc(TUser::getId);

        Page<TUser> tUserPage = tUserMapper.selectPage(page, wrapper);
        //返回分页参数
        return R.OK(tUserPage);
    }

    /**
     * 用户注册
     *
     * @param tUser
     * @return
     */
    @Override
    public R addUser(TUser tUser) {

        //--1验证用户名是否重复
        TUser user = tUserMapper.selectOne(
                new QueryWrapper<TUser>().lambda().eq(TUser::getUsername, tUser.getUsername())
        );
        if (user != null) {
            return R.ERROR(500, "用户名已经存在");
        }

        tUserMapper.insert(tUser);

        return R.OK();
    }

    /**
     * 创建配置信息
     *
     * @return
     */
    @Override
    public R getConfigFromNacos() {


        String className = myNacosConfig.getClassName();

        System.out.println("className=" + className);

        return R.OK(className);
    }

    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    @Override
    public R uploadImage(MultipartFile file) {

        try {
            String extName = FileNameUtil.extName(file.getOriginalFilename());
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);
            if (storePath == null) {
                return R.ERROR(500, "文件上传失败");
            }
            String url = "http://192.168.10.131:8888/" + storePath.getFullPath();

            return R.OK(url);

        } catch (IOException e) {
            e.printStackTrace();

            return R.ERROR(500, "上传失败");
        }
    }

    /**
     * 获取角色信息
     *
     * @param id
     * @return
     */
    @Override
    public R getUserRole(Integer id) {

        List<UserRole> roleList = tUserMapper.getUserRole(id);

        return R.OK(roleList);
    }

    /**
     * s审核用户
     *
     * @param tUser
     * @return
     */
    @Override
    public R checkUser(TUser tUser) {

        //--必须输入驳回原因
        if (tUser.getCheckStatus() == 2) {
            if (StringUtils.isEmpty(tUser.getCheckReason())) {
                return R.ERROR(500, "驳回原因不能为空");
            }
        }
        //--2 更新用户的状态
        tUserMapper.updateById(tUser);

        return R.OK();
    }

    @Override
    public R updateUser(TUser tUser) {

        //--1验证用户名是否存在
        TUser user = tUserMapper.selectOne(
                new QueryWrapper<TUser>().lambda().eq(TUser::getUsername, tUser.getUsername())
        );
        if (user == null) {
            return R.ERROR(500, "用户名不存在");
        }

        tUserMapper.updateById(tUser);

        return R.OK();

    }

    @Override
    public R delUserById(Integer id) {
        TUser tUser = tUserMapper.selectById(id);
        if (tUser == null) {
            return R.ERROR(500, "用户不存在");
        }
        tUserMapper.deleteById(id);

        return R.OK();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R delUserAll(List<TUser> userList) {

        for (TUser tUser : userList) {
            tUserMapper.deleteById(tUser.getId());
        }
        return R.OK();
    }
}




